<?php
/**
*	应用接口
*	访问地址如：http://127.0.0.1/app/rockreim/api.php?m=openagent
*/
class openagentClassAction extends openapicompanyAction
{
	/**
	*	发应用消息
	*/
	public function sendmsgAction()
	{
		$garr	= $this->getbody();
		if(!$garr['success'])return $garr;
		$da 	= $garr['data'];
		
		$agentnum 	= arrvalue($da, 'agentnum');
		$touser 	= arrvalue($da, 'touser'); //发给对应人用户名多个,分开
		$todept 	= arrvalue($da, 'todept');
		$msgtype 	= arrvalue($da, 'msgtype');
		$cont 		= arrvalue($da, 'content');
		
		if(isempt($cont))return returnerror('没有消息内容');
		if(isempt($touser) && isempt($todept))return returnerror('没有接收人');
		
		if(isempt($agentnum))return returnerror('应用编号是空的');
		$agrs		= m('agent')->getone("`cid`='$this->companyid' and `num`='$agentnum'");
		if(!$agrs)return returnerror('应用不存在');
		if($agrs['status']=='0')return returnerror('应用已停用了');
		$agentid	= $agrs['id'];
		
		$where = '';
		if(!isempt($touser)){
			if($touser=='@all'){
				$where = '`id`>0';
			}else{
				$touarr = explode(',', str_replace('|',',', $touser));
				$userin = '';
				foreach($touarr as $k1)$userin.=",'$k1'";
				$userin = substr($userin, 1);
				$where = "`user` in($userin)";
			}
		}
		if($where=='')return returnerror('没有接收人1');
		$barr = returnerror('无效msgtype:'.$msgtype.'');
		if(isempt($msgtype) || $msgtype=='text'){
			$barr = m('agent')->sendmsg($where, $agentid, $cont);
		}
		if($msgtype=='textcard'){
			if(!is_array($cont))returnerror('无效卡片消息格式');
			$title 		 = arrvalue($cont,'title');
			$description = arrvalue($cont,'description');
			if(isempt($title))returnerror('卡片消息必须要有title');
			if(isempt($description)){
				$span['mess'] = $title;
			}else{
				$span['title'] = $title;
				$span['mess']  = str_replace(array('\n',"\n",'<br>'),' ',$description);
				$cont['description']  = str_replace(array('\n',"\n"),'<br>',$description);
			}
			$barr = m('agent')->sendmsg($where, $agentid, $cont, $span);
		}
		
		if(!$barr['success'])return $barr;
		
		return returnsuccess('ok');
	}
	
	public function listdataAction()
	{
		$dbs 	= m('agent');
		$rows   = $dbs->getall('`cid`='.$this->companyid.'','*', '`sort` asc');
		foreach($rows as $k=>$rs)$rows[$k]['picurl'] = getface($rs['picurl'], $dbs->defpic);
		
		return returnsuccess(array(
			'agentlist' => $rows
		));
	}
}	